package com.example.restatr.Atcivity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.os.Looper;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.example.restatr.Atcivity.Main.MainActivity;
import com.example.restatr.Bean.CommentBean;
import com.example.restatr.R;
import com.example.restatr.Tools;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.button.MaterialButton;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class ContentAt extends AppCompatActivity {
    private LinearLayout allLl;

    private Toolbar tb;
    private TextView barTitle;
    private EditText search;

    private NestedScrollView NS;
    private CoordinatorLayout CL;
    private AppBarLayout appBar;
    private WebView web;

    private LinearLayout bmLl;
    private TextView date;
    private ImageView likeImage;
    private TextView likeNum;
    private ImageView ReadNumImg;
    private TextView ReadNum;
    private TextView commentNum;

    private RelativeLayout PLRl;
    private RecyclerView pl;
    private LinearLayout Null;

    private RelativeLayout RLPl;
    private EditText plEdText;
    private MaterialButton button;

    private List<CommentBean.RowsBean> CommentRowsBeans = new ArrayList<>();

    private boolean isSingUp, isLike;
    private int numLike, numRead;
    private LinearLayout loading;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_content_at);


        allLl = findViewById(R.id.all_ll);

        tb = findViewById(R.id.toolbar);
        barTitle = findViewById(R.id.bar_Title);
        search = findViewById(R.id.search);

        NS = findViewById(R.id.NS);
        CL = findViewById(R.id.CL);
        appBar = findViewById(R.id.appBar);
        web = findViewById(R.id.web);

        bmLl = findViewById(R.id.bm_ll);
        date = findViewById(R.id.date);
        likeImage = findViewById(R.id.likeImage);
        likeNum = findViewById(R.id.likeNum);
        ReadNumImg = findViewById(R.id.ReadNumImg);
        ReadNum = findViewById(R.id.ReadNum);
        commentNum = findViewById(R.id.commentNum);
        Null = findViewById(R.id.Null);

        PLRl = findViewById(R.id.PL_rl);
        pl = findViewById(R.id.pl);

        RLPl = findViewById(R.id.RL_pl);
        plEdText = findViewById(R.id.pl_edText);
        button = findViewById(R.id.button);
        loading = findViewById(R.id.loading);

        numLike = getIntent().getIntExtra("likeNum", 0);
        numRead = getIntent().getIntExtra("ReadNum", 0);
        isLike = getIntent().getBooleanExtra("isLike", false);
        likeNum.setText(String.valueOf(numLike));
        ReadNum.setText(String.valueOf(numRead));
        date.setText(getIntent().getStringExtra("date"));
        commentNum.setText(getIntent().getStringExtra("commentNum"));
        if (isLike) {
            likeImage.setImageResource(R.drawable.ic_baseline_favorite_24);
        } else {
            likeImage.setImageResource(R.drawable.ic_baseline_favorite_border_24);
        }
        if (getIntent().getStringExtra("type") != null) {
            switch (getIntent().getStringExtra("type")) {
                case "default":
                    appBar.removeAllViews();
                    CL.setVisibility(View.GONE);
                    RLPl.setVisibility(View.GONE);
                    NS.setVisibility(View.VISIBLE);
                    allLl.addView(web);
                    break;
                case "Hd":
                    new Thread(()->{
                        GetComment("/prod-api/api/activity/comment/list?activityId=", "");
                    }).start();
                    isSingUp = getIntent().getBooleanExtra("isSingUp", false);
                    if (isSingUp) {
                        ReadNumImg.setBackgroundResource(R.drawable.ic_round_select_person_add_24);
                    } else {
                        ReadNumImg.setBackgroundResource(R.drawable.ic_round_person_add_24);
                    }
                    break;
                case "lj":
                    loading.setVisibility(View.VISIBLE);
                    new Thread(()->{
                        GetComment("/prod-api/api/garbage-classification/news-comment/list?newsId=", MainActivity.sp.getString("token", ""));
                    }).start();
                    break;
            }
        }

        Tools.SetBarTitle(tb, barTitle, getIntent().getStringExtra("title"), search, ContentAt.this, false);
        web.getSettings().setJavaScriptEnabled(true);
        web.loadData(getIntent().getStringExtra("content"), "text/html", "UTF-8");
        web.setWebViewClient(new webClient());
        plEdText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (plEdText.getText().toString().length() > 0) {
                    button.setVisibility(View.VISIBLE);
                } else {
                    button.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


    }

    /**
     * 使图片宽度不超过屏幕宽度
     */
    private void imageReset() {
        web.loadUrl("javascript:(function(){\n" +
                "    var objs=document.getElementsByTagName('img');\n" +
                "for(var i=0;i<objs.length;i++){\n" +
                "    var img=objs[i];\n" +
                "    img.style.maxWidth='100%';\n" +
                "    img.style.height='auto';\n" +
                "}\n" +
                "})();");
    }

    public void onClick(View view) {
        switch (view.getId()) {
            //点赞
            case R.id.dianz:
                //判断是否为已点赞
                if (!isLike) {
                    //判断是否是新闻页面，实现点赞功能
                    if (CommentRowsBeans.size() > 0) {
                        numLike++;
                        likeNum.setText(String.valueOf(numLike));
                        likeImage.setImageResource(R.drawable.ic_baseline_favorite_24);
                        isLike = true;
                    } else {
                        new Thread(() -> {
                            try {
                                JSONObject jx = new JSONObject(Tools.Put("/prod-api/press/press/like/" + getIntent().getIntExtra("NewsId", 0), MainActivity.sp.getString("token", ""), ""));
                                String msg = jx.getString("msg");
                                int code = jx.getInt("code");
                                runOnUiThread(() -> {
                                    Toast.makeText(ContentAt.this, msg, Toast.LENGTH_SHORT).show();
                                    if (code == 200) {
                                        numLike++;
                                        likeNum.setText(String.valueOf(numLike));
                                        likeImage.setImageResource(R.drawable.ic_baseline_favorite_24);
                                        isLike = true;
                                    }
                                });
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }).start();
                    }
                } else {
                    numLike--;
                    likeNum.setText(String.valueOf(numLike));
                    likeImage.setImageResource(R.drawable.ic_baseline_favorite_border_24);
                    isLike = false;
                }
                break;
            //报名
            case R.id.singUp:
                if (getIntent().getStringExtra("type") != null) {
                    if (!isSingUp) {
                        new Thread(() -> {
                            try {
                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put("activityId", getIntent().getIntExtra("id", -1));
                                JSONObject jx = new JSONObject(Tools.Post("/prod-api/api/activity/signup", MainActivity.sp.getString("token", ""), jsonObject.toString()));
                                int code = jx.getInt("code");
                                String msg = jx.getString("msg");
                                runOnUiThread(() -> {
                                    if (code == 200) {
                                        ReadNumImg.setBackgroundResource(R.drawable.ic_round_select_person_add_24);
                                        isSingUp = true;
                                        numRead++;
                                        ReadNum.setText(String.valueOf(numRead));
                                        Toast.makeText(ContentAt.this, "报名成功", Toast.LENGTH_SHORT).show();
                                    } else {
                                        Toast.makeText(ContentAt.this, msg, Toast.LENGTH_SHORT).show();
                                    }
                                });

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }).start();
                    }
                }
                break;
            //评论
            case R.id.button:
                String Comment = plEdText.getText().toString();
                if (getIntent().getStringExtra("type").equals("Hd")) {
                    ReNewComment("activityId", Comment, "/prod-api/api/activity/comment", "/prod-api/api/activity/comment/list?activityId=");
                } else if (getIntent().getStringExtra("type").equals("xw")) {
                    ReNewComment("newsId", Comment, "/prod-api/press/pressComment", "/prod-api/press/comments/list?newsId=");
                }else if (getIntent().getStringExtra("type").equals("lj")){
                    ReNewComment("newsId", Comment, "/prod-api/api/garbage-classification/news-comment", "/prod-api/api/garbage-classification/news-comment/list?newsId=");
                }
                break;
        }
    }

    //获取评论列表
    private void GetComment(String link, String token) {
        CommentRowsBeans.clear();
        String id = Tools.Get(link + getIntent().getIntExtra("id", -1), token);
        Log.d("TAG", "id: " + getIntent().getIntExtra("id", -1));
        Log.d("TAG", "GetComment: " + id);
        List<CommentBean.RowsBean> rows = new Gson().fromJson(id, CommentBean.class).getRows();
        CommentRowsBeans.addAll(rows);
        SetPlShow();
    }

    //设置评论显示
    private void SetPlShow() {
        runOnUiThread(() -> {
            if (CommentRowsBeans.size() > 0) {
                pl.setVisibility(View.VISIBLE);
                Null.setVisibility(View.GONE);
                loading.setVisibility(View.GONE);
                if (getIntent().getStringExtra("type").equals("xw")) {
                    //按时间排序
                    CommentRowsBeans = CommentRowsBeans.stream().sorted(Comparator.comparing(CommentBean.RowsBean::getCommentDate).reversed()).collect(Collectors.toList());
                }
                pl.setAdapter(new PlListAdapter(CommentRowsBeans));
            } else {
                Null.setVisibility(View.VISIBLE);
                pl.setVisibility(View.GONE);
            }
        });
    }

    //发表评论
    private void ReNewComment(String type, String Comment, String putCommentLink, String GetCommentLink) {
        loading.setVisibility(View.VISIBLE);
        pl.setVisibility(View.GONE);
        new Thread(() -> {
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put(type, getIntent().getIntExtra("id", -1));
                jsonObject.put("content", Comment);
                JSONObject jx = new JSONObject(Tools.Post(putCommentLink, MainActivity.sp.getString("token", ""), jsonObject.toString()));
                String msg = jx.getString("msg");
                int code = jx.getInt("code");
                if (code == 200) {
                    GetComment(GetCommentLink,  MainActivity.sp.getString("token",""));
                }
                Looper.prepare();
                plEdText.setText("");
                Toast.makeText(ContentAt.this, msg, Toast.LENGTH_SHORT).show();
                Looper.loop();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }).start();
    }

    class webClient extends WebViewClient {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            //当页面加载完成后调用方法，使图片宽度不超过屏幕宽度
            imageReset();
        }
    }

    class PlListAdapter extends RecyclerView.Adapter<PlListAdapter.PlListViewHolder> {
        private List<CommentBean.RowsBean> rowsBeans = new ArrayList<>();

        public PlListAdapter(List<CommentBean.RowsBean> rowsBeans) {
            this.rowsBeans = rowsBeans;
        }

        @NonNull
        @Override
        public PlListAdapter.PlListViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View inflate = LayoutInflater.from(ContentAt.this).inflate(R.layout.pj_list_item, parent, false);
            return new PlListAdapter.PlListViewHolder(inflate);
        }

        @Override
        public void onBindViewHolder(@NonNull PlListAdapter.PlListViewHolder holder, int position) {

            if (getIntent().getStringExtra("type").equals("lj")) {
                holder.date.setText(rowsBeans.get(position).getCreateTime());
                holder.name.setText("用户" + rowsBeans.get(position).getUserId());
            } else {
                Glide.with(ContentAt.this)
                        .load(Tools.ip + "/prod-api" + rowsBeans.get(position).getAvatar())
                        .transform(new CircleCrop())
                        .placeholder(R.drawable.ic_baseline_account_circle_24)
                        .into(holder.head);

                holder.name.setText(rowsBeans.get(position).getNickName());
                if (getIntent().getStringExtra("type").equals("Hd")) {
                    holder.date.setText(rowsBeans.get(position).getCommentTime());
                } else if (getIntent().getStringExtra("type").equals("xw")) {
                    holder.date.setText(rowsBeans.get(position).getCommentDate());
                }
            }

            holder.content.setText(rowsBeans.get(position).getContent());
            holder.score.setVisibility(View.GONE);
            holder.reply.setVisibility(View.GONE);
            holder.level.setVisibility(View.GONE);
        }

        @Override
        public int getItemCount() {
            return rowsBeans.size();
        }

        class PlListViewHolder extends RecyclerView.ViewHolder {
            ImageView head;
            TextView name;
            TextView date;
            RatingBar score;
            TextView level;
            TextView content;
            CardView reply;
            TextView replyTime;
            TextView replyContent;

            public PlListViewHolder(@NonNull View itemView) {
                super(itemView);
                head = itemView.findViewById(R.id.head);
                name = itemView.findViewById(R.id.name);
                date = itemView.findViewById(R.id.date);
                score = itemView.findViewById(R.id.score);
                level = itemView.findViewById(R.id.level);
                content = itemView.findViewById(R.id.content);
                reply = itemView.findViewById(R.id.reply);
                replyTime = itemView.findViewById(R.id.replyTime);
                replyContent = itemView.findViewById(R.id.replyContent);
            }
        }
    }
}